from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import permissions
from django.db.models import Count, Sum
from orders.models import Order
from products.models import Product
from django.utils import timezone
from datetime import date
from delivery.models import DeliveryTask, DeliveryArea, DeliverymanArea # Added DeliveryArea, DeliverymanArea
from django.db.models import Count, Q # Added Q
from users.models import User  # 添加这一行导入User模型

class DashboardStatsView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request):
        user = request.user
        stats = {}
        today = date.today()

        # 根据用户角色返回不同的统计数据
        if user.role == 'admin':
            # 管理员可以看到所有统计数据
            stats = {
                'total_users': User.objects.count(),
                'total_orders': Order.objects.count(),
                'total_products': Product.objects.count(),
                'total_deliveries': DeliveryTask.objects.count(),
                'pending_deliveries': DeliveryTask.objects.filter(status__in=['pending', 'assigned']).count(), # Corrected pending definition
                'pending_orders': Order.objects.filter(status='pending').count(),
                'low_stock_products': Product.objects.filter(stock__lt=10).count(),
            }
        elif user.role == 'delivery_admin': # Added delivery_admin role
            pending_tasks_count = DeliveryTask.objects.filter(status__in=['pending', 'assigned']).count()
            delivering_tasks_count = DeliveryTask.objects.filter(status='delivering').count()
            completed_today_count = DeliveryTask.objects.filter(
                status='completed', 
                actual_delivery_time__date=today
            ).count()
            active_deliverymen_count = User.objects.filter(role='deliveryman', is_active=True).count()

            task_status_distribution_data = DeliveryTask.objects.values('status').annotate(count=Count('status'))
            task_status_distribution = {item['status']: item['count'] for item in task_status_distribution_data}
            # Ensure all expected statuses are present, even if count is 0
            for status_key in ['pending', 'assigned', 'delivering', 'completed', 'cancelled']:
                if status_key not in task_status_distribution:
                    task_status_distribution[status_key] = 0
            
            # Combine pending and assigned for the chart as per frontend expectation if needed, or adjust frontend
            # For now, returning detailed breakdown. Frontend might need adjustment or this logic can be adapted.
            # The frontend chart expects: pending, delivering, completed, cancelled.
            # We can map 'assigned' to 'pending' for the chart if that's the desired aggregation.
            chart_task_status_distribution = {
                'pending': task_status_distribution.get('pending', 0) + task_status_distribution.get('assigned', 0),
                'delivering': task_status_distribution.get('delivering', 0),
                'completed': task_status_distribution.get('completed', 0),
                'cancelled': task_status_distribution.get('cancelled', 0),
            }

            area_delivery_data = DeliveryTask.objects.filter(
                deliveryman__isnull=False, 
                deliveryman__delivery_areas__isnull=False
            ).values('deliveryman__delivery_areas__area__name').annotate(count=Count('id')).order_by('-count')
            
            area_delivery_distribution = {item['deliveryman__delivery_areas__area__name']: item['count'] for item in area_delivery_data}

            urgent_tasks_list = list(DeliveryTask.objects.filter(
                priority='high', 
                status__in=['pending', 'assigned', 'delivering']
            ).values('id', 'delivery_number', 'sales_order__order_number', 'sales_order__customer__username', 'sales_order__address', 'status')[:10]) # Limiting to 10 for dashboard
            # Renaming fields to match frontend expectations
            urgent_tasks_formatted = [
                {
                    'id': task['id'],
                    'delivery_number': task['delivery_number'],
                    'order_number': task['sales_order__order_number'],
                    'customer_name': task['sales_order__customer__username'],
                    'address': task['sales_order__address'],
                    'status': task['status'],
                }
                for task in urgent_tasks_list
            ]

            stats = {
                'pending_tasks': pending_tasks_count,
                'delivering_tasks': delivering_tasks_count,
                'completed_today': completed_today_count,
                'active_deliverymen': active_deliverymen_count,
                'task_status_distribution': chart_task_status_distribution, # Use the chart-specific distribution
                'area_delivery_distribution': area_delivery_distribution,
                'urgent_tasks': urgent_tasks_formatted,
            }

        elif user.role == 'salesman':
            # 销售员可以看到订单相关统计
            stats = {
                'total_orders': Order.objects.count(),
                'pending_orders': Order.objects.filter(status='pending').count(),
                'completed_orders': Order.objects.filter(status='completed').count(),
            }
        elif user.role == 'purchaser':
            # 采购员可以看到库存相关统计
            stats = {
                'total_products': Product.objects.count(),
                'low_stock_products': Product.objects.filter(stock__lt=10).count(),
            }
        elif user.role == 'deliveryman':
            # 配送员可以看到配送相关统计
            stats = {
                'total_deliveries': Delivery.objects.count(),
                'pending_deliveries': Delivery.objects.filter(status='pending').count(),
            }
        elif user.role == 'customer':
            # 客户可以看到自己的订单统计
            stats = {
                'total_orders': Order.objects.filter(customer=user).count(),
                'pending_orders': Order.objects.filter(customer=user, status='pending').count(),
                'completed_orders': Order.objects.filter(customer=user, status='completed').count(),
            }

        return Response(stats)